//处理各种类型转换
package common

import (
	"crypto/md5"
	"encoding/hex"
	"strconv"
)

func IntToString(i int) (s string) {
	s = strconv.Itoa(i)
	return
}

func StringToInt(s string) (i int, err error) {
	i, err = strconv.Atoi(s)
	return
}

func StringToFloat(s string) (f float64, err error) {
	f, err = strconv.ParseFloat(s, 64)
	return
}

func Formatfloat(f float64, i int) (sf string) { //四舍五入去小数 f为float数，i为要取得小数点后几位
	sf = strconv.FormatFloat(f, 'f', i, 64)
	return
}

func Substr(str string, start, length int) string { //字符串截取
	rs := []rune(str)
	rl := len(rs)
	end := 0

	if start < 0 {
		start = rl - 1 + start
	}
	end = start + length

	if start > end {
		start, end = end, start
	}

	if start < 0 {
		start = 0
	}
	if start > rl {
		start = rl
	}
	if end < 0 {
		end = 0
	}
	if end > rl {
		end = rl
	}

	return string(rs[start:end])
}

func Contains(list []string, elem string) bool {
	for _, t := range list {
		if t == elem {
			return true
		}
	}
	return false
}

func RemoveFromSlice(list []string, elem string) []string {
	j := -1
	for i, t := range list {
		if t == elem {
			j = i
			break
		}
	}
	if j == 0 {
		list = list[1:]
	} else if j > 0 {
		list = append(list[:j], list[j+1:]...)
	}

	return list
}

func MD5(str string) string {
	h := md5.New()
	h.Write([]byte(str))

	return hex.EncodeToString(h.Sum(nil)) // 输出加密结果
}

func InterfaceToString(i interface{}) string {
	return i.(string)
}
